class ProductsController < ApplicationController
  require 'nokogiri'
  require 'open-uri'
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  def home

  end

  # GET /products
  # GET /products.json
  def index
    @products = Product.all
  end

  # GET /products/1
  # GET /products/1.json
  def show
  end

  # GET /products/new
  def new

  end

  # GET /products/1/edit
  def edit
  end

  # POST /products
  # POST /products.json
  def create
    content =params[:content]
    pid=/\d+/.match(/[?,&]id=\d+\&/.match(content)[0]).to_s
    #如果不是通过url 那通过title来的查找 
    
    # print pid
    @product = Product.find_by(pid: pid)
    if @product==nil

      page = Nokogiri::HTML(open("http://s.etao.com/detail/#{@pid}.html"))
      title=page.css(".product-title")[0]['title']
      url = 'http://s.etao.com/detail/#{@pid}.html'
      img=page.css('.product-picture')[0]['img-src']
      price=page.css('.original-price')[0].text[1..-1]
      @product = Product.new(pid: pid,title: title ,url: url, img: img)
      @price = Price.new(pid: pid,price: price)

      respond_to do |format|

      if @product.save && @price.save
        format.html { redirect_to root_path, notice: 'Product was successfully created.' }
        format.js
        return 
      else
        format.html { render action: 'new' }
        format.js
        return
      end
    end

    else 
      @prices =@product.prices
      #redirect_to root_path
      return

    end


    
  end

  # PATCH/PUT /products/1
  # PATCH/PUT /products/1.json
  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /products/1
  # DELETE /products/1.json
  def destroy
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url }
      format.json { head :no_content }
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_product
    @product = Product.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def product_params
    params.require(:product).permit(:pid, :title, :img, :price)
  end
end
